package com.cloud.cloudvideo.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.pool.vendor.SybaseExceptionSorter;
import com.cloud.cloudvideo.entity.TreePojo;
import com.cloud.cloudvideo.entity.SysRole;
import com.cloud.cloudvideo.entity.SysRolePermission;
import com.cloud.cloudvideo.entity.SysRolePermissionExample;
import com.cloud.cloudvideo.mapper.SysRoleMapper;
import com.cloud.cloudvideo.mapper.SysRolePermissionMapper;
import com.cloud.cloudvideo.service.RoleService;

@Service
public class RoleServiceImpl implements RoleService {

	@Autowired
	private SysRoleMapper roleMapper;

	@Autowired
	private SysRolePermissionMapper rolePermissionMapper;

	@Override
	public List<SysRole> list() {
		return roleMapper.selectByExample(null);
	}

	@Override
	public void modifyRole(SysRole role) {
		if (null == role.getId()) {
			role.setCreateBy(1L);
			role.setCreateTime(new Date());
			roleMapper.insertSelective(role);
		} else {
			role.setUpdateTime(new Date());
			roleMapper.updateByPrimaryKeySelective(role);
		}
	}

	@Override
	public void del(Integer id) {
		roleMapper.deleteByPrimaryKey(id.longValue());
	}

	@Override
	public SysRole roleInfo(Integer id) {
		return roleMapper.selectByPrimaryKey(id.longValue());
	}

	/**
	 * 修改角色权限
	 */
	@Override
	@Transactional
	public void modifyRolePermission(List<TreePojo> pojo,Integer roleId) {
		SysRolePermissionExample example = new SysRolePermissionExample();
		example.createCriteria().andRoleIdEqualTo(roleId.longValue());
		List<SysRolePermission> list = rolePermissionMapper.selectByExample(example);
		if(!list.isEmpty()) {//修改
			rolePermissionMapper.deleteByExample(example);
		}
		for (int i = 0; i < pojo.size(); i++) {
			TreePojo sysPermissionPojo = pojo.get(i);
			List<TreePojo> children = sysPermissionPojo.getChildren();
			next(children,roleId);
		}
		
	}

	private void next(List<TreePojo> tmp, Integer roleId){
		if(null != tmp && !tmp.isEmpty()){
			for(int i = 0; i < tmp.size(); i++){
				TreePojo sysPermissionPojo = tmp.get(i);
				SysRolePermission permission = new SysRolePermission();
				permission.setRoleId(roleId.longValue());
				permission.setPermissionId(sysPermissionPojo.getId());
				rolePermissionMapper.insertSelective(permission);
				List<TreePojo> children = sysPermissionPojo.getChildren();
				next(children,roleId);
			}
		}
	}

	@Override
	public Integer[] allPermissionId(Integer roleid) {
		Integer[] ids = rolePermissionMapper.findIdByRoleId(roleid);
		return ids;
	}


}
